package com.campus.config;

import com.campus.filter.TokenFilter;
import com.campus.handler.AuthenticationExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Autowired
    private AuthenticationExceptionHandler authenticationExceptionHandler;
    @Autowired
    private TokenFilter tokenFilter;
    @Autowired
    private DemoConfiguration.Security security;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        List<String> permitAllPaths = security.getPermitAllPath();

        // 配置不需要认证的请求（可以通过配置文件进行修改）
        if (!CollectionUtils.isEmpty(permitAllPaths)) {
            permitAllPaths.forEach(path -> {
                try {
                    http.authorizeHttpRequests().requestMatchers(path).permitAll();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }

        // 关闭csrf因为不使用session
        http.cors().and().csrf().disable()
                // 不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeHttpRequests()
                // 根据角色进行路径控制
                .requestMatchers("/uaa").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")  // 管理员角色
                .requestMatchers("/teacher/**").hasRole("TEACHER")  // 任课教师角色
                .requestMatchers("/assistant/**").hasRole("ASSISTANT")  // 教辅教师角色
                .anyRequest().authenticated()  // 其他请求需要认证
                .and()
                // 配置异常处理
                .exceptionHandling()
                .authenticationEntryPoint(authenticationExceptionHandler);

        // 配置token拦截过滤器
        http.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    /**
     * 身份认证管理器，调用authenticate()方法完成认证
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    /**
     * 密码加密器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
